package com.investindo.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import net.sf.json.JSONArray;

import com.investindo.bean.Usuario;
import com.investindo.dao.EuInvestindoConnectionFactory;

public class UsuarioUtil {

	Connection conn = null;
	PreparedStatement stmt = null;
	String sql = null;
	static Usuario usuario;

	public int login(Usuario usuario) {
		try {
			this.usuario = usuario;
			// usuario.setEmail("oiii");
			// usuario.setSenha("serser");
			conn = EuInvestindoConnectionFactory.getConn();

			sql = "select (id_usuario) from usuario ";
			sql = sql + " where (email = ? and senha = ?);";

			stmt = conn.prepareStatement(sql);

			stmt.setString(1, usuario.getEmail());
			stmt.setString(2, usuario.getSenha());

			ResultSet rs = stmt.executeQuery();
			if (rs.next()) {
				this.usuario.setId(rs.getInt(1));
			}

		} catch (Exception e) {
			System.out.println(e);
			return -1;
		}

		return this.usuario.getId();

	}

	public String getJson(String nomeDado) {
		JSONArray jsonArray = JSONArray.fromObject(usuario);
		String returnJson = "{\"" + nomeDado + "\":" + jsonArray + "}";
		System.out.println(returnJson);
		return returnJson;
	}

	public String novoUsuario(Usuario usuario) {
		try {

			conn = EuInvestindoConnectionFactory.getConn();

			sql = "Insert into usuario ()";
			sql = "INSERT INTO usuario(email, nome, senha, cpf, valor_caixa, recebe_info_cel) ";
			sql = sql + " VALUES (?, ?, ?, ?, ?, ?) RETURNING id_usuario;";

			stmt = conn.prepareStatement(sql);

			stmt.setString(1, usuario.getEmail());
			stmt.setString(2, usuario.getNome());
			stmt.setString(3, usuario.getSenha());

			stmt.setString(4, usuario.getCpf());
			stmt.setDouble(5, usuario.getValorCaixa());
			stmt.setBoolean(6, usuario.isInfoCel());

			ResultSet rs = stmt.executeQuery();
			if (rs.next()) {
				usuario.setId(rs.getInt(1));
			}
			return getJson("logado");

		} catch (Exception e) {
			System.out.println(e);
			return "erro";
		}

		finally {

			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException sqlex) {
					// ignore -- as we can't do anything about it here
				}

				stmt = null;
			}

			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException sqlex) {
					// ignore -- as we can't do anything about it here
				}

				conn = null;
			}
		}

	}
}
